import React from 'react';
import { Message } from 'antd';
import * as echarts from 'echarts';
import 'echarts-gl';
import { connect } from 'umi';

import { HttpCode } from '#/utils/contacts.js';
import { TRDefault } from '@/components';
import { EchartsType } from '@/pages/Tianji/DayRollingTradeStrategy/constant.js';

import styles from './index.less';

import {
  fetch3DChartData,
  fetchBenefitsComputedChartData,
  fetchPriceComputedChartData,
  fetchPowerComputedChartData,
} from '@/pages/Tianji/DayRollingTradeStrategy/services';
import { useThemeChange } from '@/hooks';
import { getCssVariableValue } from '@/utils/utils';

const EchartsShow = ({
  menuCode,
  tradeSeqId,
  stationId,
  echartsHourOrder,
  echartsBenefit,
  echartsBenefitStep,
  echartsPrice,
  echartsPower,
  selectedEcharts,
  strategyId,
  echartsRefreshTag,
  dispatch,
}) => {
  const [chartDom3d, setChartDom3d] = React.useState(null),
    [chartDom2d, setChartDom2d] = React.useState(null),
    [showEcharts, setShowEcharts] = React.useState(false),
    // 3d数据
    [threeDimensionData, setThreeDimensionData] = React.useState(null),
    // 收益截面数据
    [benefitsChartData, setBenefitsChartData] = React.useState(null),
    // 价格截面数据
    [priceChartData, setPriceChartData] = React.useState(null),
    // 电量截面数据
    [powerChartData, setPowerChartData] = React.useState(null);

  const { theme } = useThemeChange();
  /**
   * 当策略id || 选中时点 || 选中的图形发生变化时，重新调用接口获取数据
   */
  React.useEffect(() => {
    if (strategyId) {
      echartsRefresh();
    }
  }, [echartsHourOrder, selectedEcharts, strategyId]);

  /**
   * 当图形刷新标识改变时，刷新图形
   */
  React.useEffect(() => {
    if (echartsRefreshTag) {
      echartsRefresh();
    }
  }, [echartsRefreshTag]);

  /**
   * 当收益变动目标 || 收益截面精度发生变化时，重新获取收益截面数据
   */
  React.useEffect(() => {
    if (tradeSeqId && stationId && selectedEcharts === EchartsType.BENEFIT) {
      fetchBenefitsComputedChartDataAsync();
    }
  }, [echartsBenefit, echartsBenefitStep]);

  /**
   * 当价格水平发生变化时，重新获取电价截面数据
   */
  React.useEffect(() => {
    if (tradeSeqId && stationId && selectedEcharts === EchartsType.PRICE) {
      fetchPriceComputedChartDataAsync();
    }
  }, [echartsPrice]);

  /**
   * 当交易量发生变化时，重新获取电量截面数据
   */
  React.useEffect(() => {
    if (tradeSeqId && stationId && selectedEcharts === EchartsType.POWER) {
      fetchPowerComputedChartDataAsync();
    }
  }, [echartsPower]);

  /**
   * 当三维图形数据发生变化时，重新初始化三维图形
   */
  React.useEffect(() => {
    if (!threeDimensionData) return;
    init3dModel();
  }, [threeDimensionData]);

  /**
   * 当收益截面数据发生变化时，重新初始化收益截面图形
   */
  React.useEffect(() => {
    if (!benefitsChartData) return;
    init2dModel();
  }, [benefitsChartData]);

  /**
   * 当价格截面数据发生变化时，重新初始化价格截面图形
   */
  React.useEffect(() => {
    if (!priceChartData) return;
    init2dModel();
  }, [priceChartData]);

  /**
   * 当电量截面数据发生变化时，重新初始化电量截面图形
   */
  React.useEffect(() => {
    if (!powerChartData) return;
    init2dModel();
  }, [powerChartData]);

  React.useEffect(() => {
    if (powerChartData || priceChartData || benefitsChartData) {
      setTimeout(() => {
        init2dModel();
      }, 1);
    }
    if (threeDimensionData) {
      setTimeout(() => {
        init3dModel();
      }, 1);
    }
  }, [theme]);

  const init3dModel = () => {
    chartDom3d && chartDom3d.dispose();
    var chartDom = document.getElementById('3dModel');
    var myChart = echarts.init(chartDom);
    var option = {
      tooltip: {
        backgroundColor: '#161A1D',
        borderColor: 'transparent',
        textStyle: {
          color: '#d3d4d4',
        },
        formatter: (params) => {
          let str = `
           ${params.seriesName}
           <br />
           ${params.marker}
           <br />
           <div style="width: 140px; display:flex; justify-content:space-between;"><span>交易量</span><span>${params.data[0].toFixed(
             3,
           )}</span></div>
           <div style="width: 140px; display:flex; justify-content:space-between;"><span>交易价</span><span>${params.data[1].toFixed(
             2,
           )}</span></div>
           <div style="width: 140px; display:flex; justify-content:space-between;"><span>收益浮动</span><span>${params.data[2].toFixed(
             2,
           )}</span></div>
          `;
          return str;
        },
      },
      backgroundColor: 'transparent',
      visualMap: {
        seriesIndex: 0, // 作用于第一个series，不设置的话，第二个series设置颜色无效
        show: false,
        dimension: 2,
        min: threeDimensionData.rMin,
        max: threeDimensionData.rMax,
        inRange: {
          color: [
            '#002766',
            '#0050b3',
            '#1890ff',
            '#69c0ff',
            '#bae7ff',

            '#ffccc7',
            '#ff7875',
            '#f5222d',
            '#a8071a',
            '#5c0011',
          ],
        },
      },
      xAxis3D: {
        type: 'value',
        name: '交易量',
        nameTextStyle: {
          color: getCssVariableValue('--chart-y-line'),
          fontSize: 14,
        },
      },
      yAxis3D: {
        type: 'value',
        name: '交易价',
        nameTextStyle: {
          color: getCssVariableValue('--chart-y-line'),
          fontSize: 14,
        },
      },
      zAxis3D: {
        type: 'value',
        name: '收益',
        nameTextStyle: {
          color: getCssVariableValue('--chart-y-line'),
          fontSize: 14,
        },
      },
      grid3D: {
        viewControl: {
          zoomSensitivity: 0, // 禁止缩放
          distance: 220, // 视角距离主体的距离
          alpha: 10,
          minAlpha: 0,
          maxAlpha: 60,
          beta: 30,
          minBeta: 0,
          maxBeta: 80,
        },
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisPointer: {
          lineStyle: {
            color: getCssVariableValue('--bd-primary'),
          },
        },
        axisLabel: {
          textStyle: {
            color: getCssVariableValue('--chart-font-color'),
          },
        },
        axisTick: {
          show: false,
        },
        top: -50,
        left: 26,
      },
      series: [
        {
          type: 'surface',
          wireframe: {
            lineStyle: {
              color: '#4e5154',
            },
          },
          name: '交易量-交易价-收益变动',
          data: threeDimensionData.coordinate,
        },
        {
          type: 'surface',
          wireframe: {
            show: false,
          },
          tooltip: {
            show: false,
          },
          itemStyle: {
            color: '#ffffff',
            opacity: 0.6,
          },
          equation: {
            x: {
              step: (threeDimensionData.qMax - threeDimensionData.qMin) / 50,
              min: threeDimensionData.qMin - Math.abs(threeDimensionData.qMin * 0.2),
              max: threeDimensionData.qMax + Math.abs(threeDimensionData.qMin * 0.2),
            },
            y: {
              step: (threeDimensionData.pMax - threeDimensionData.pMin) / 50,
              min: threeDimensionData.pMin - Math.abs(threeDimensionData.pMin * 0.2),
              max: threeDimensionData.pMax + Math.abs(threeDimensionData.pMin * 0.2),
            },
            z: function () {
              return 0;
            },
          },
        },
      ],
    };

    myChart.setOption(option);
    setChartDom3d(myChart);
  };

  const init2dModel = () => {
    chartDom2d && chartDom2d.dispose();

    let chartData = {},
      xAxisName = '',
      yAxisName = '',
      tooltipX = '',
      tooltipY = '';

    switch (selectedEcharts) {
      case EchartsType.BENEFIT:
        chartData = benefitsChartData;
        xAxisName = '量(MWh)';
        yAxisName = '价(元/MWh)';
        tooltipX = '交易量';
        tooltipY = '交易价格';
        break;
      case EchartsType.PRICE:
        chartData = priceChartData;
        xAxisName = '量(MWh)';
        yAxisName = '收益(元)';
        tooltipX = '交易量';
        tooltipY = '收益变动';
        break;
      case EchartsType.POWER:
        chartData = powerChartData;
        xAxisName = '价(元/MWh)';
        yAxisName = '收益(元)';
        tooltipX = '交易价格';
        tooltipY = '收益变动';
        break;
    }

    var chartDom = document.getElementById('2dModel');
    var myChart = echarts.init(chartDom);
    var option = {
      color: ['#FF9F0A'],
      tooltip: {
        trigger: 'axis',
        backgroundColor: '#161A1D',
        borderColor: 'transparent',
        textStyle: {
          color: '#d3d4d4',
        },
        formatter: (params) => {
          let str = `
           ${tooltipX} ${params[0].name}
           <br />
           ${params[0].marker} ${tooltipY} ${params[0].data}
          `;
          return str;
        },
      },
      grid: {
        right: 90,
      },
      xAxis: {
        type: 'category',
        name: xAxisName,
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        data: chartData.xAxisData,
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisTick: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisPointer: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
            type: 'solid',
          },
        },
        axisTick: {
          show: false,
        },
      },
      yAxis: {
        type: 'value',
        name: yAxisName,
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        scale: true,
        axisLine: {
          show: true,
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        splitLine: {
          show: false,
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisTick: {
          show: false,
        },
      },
      series: [
        {
          data: chartData.yAxisData,
          type: 'line',
          smooth: true,
          symbol: 'none',
        },
      ],
    };
    myChart.setOption(option);
    setChartDom2d(myChart);
  };

  // 获取三维模型的图表数据
  const fetch3DChartDataAsync = async () => {
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await fetch3DChartData({
      sequenceId: tradeSeqId,
      unitId: stationId,
      menuCode: menuCode,
      hourOrder: echartsHourOrder,
      qStep: 50,
      pStep: 50,
    });
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (res?.data?.coordinate?.length) {
        setShowEcharts(true);
        setThreeDimensionData(res.data);
      } else {
        setShowEcharts(false);
      }
    } else {
      Message.error(res.message || '获取三维模型数据失败');
      setShowEcharts(false);
    }
  };

  // 获取计算收益截面图表数据
  const fetchBenefitsComputedChartDataAsync = async () => {
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await fetchBenefitsComputedChartData({
      sequenceId: tradeSeqId,
      unitId: stationId,
      menuCode: menuCode,
      hourOrder: echartsHourOrder,
      benefits: echartsBenefit,
      qStep: echartsBenefitStep,
      pStep: echartsBenefitStep,
    });
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (res?.data?.xAxisData?.length) {
        setShowEcharts(true);
        let data = JSON.parse(JSON.stringify(res.data));
        data.xAxisData = data.xAxisData.map((item) => item.toFixed(3));
        data.yAxisData = data.yAxisData.map((item) => item.toFixed(2));
        setBenefitsChartData(data);
      } else {
        setShowEcharts(false);
      }
    } else {
      Message.error(res.message || '获取量-价截面模型数据失败');
      setShowEcharts(false);
    }
  };

  // 获取计算交易价格截面图表数据
  const fetchPriceComputedChartDataAsync = async () => {
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await fetchPriceComputedChartData({
      sequenceId: tradeSeqId,
      unitId: stationId,
      menuCode: menuCode,
      hourOrder: echartsHourOrder,
      price: echartsPrice,
      qStep: 50,
    });
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (res?.data?.xAxisData?.length) {
        setShowEcharts(true);
        let data = JSON.parse(JSON.stringify(res.data));
        data.xAxisData = data.xAxisData.map((item) => item.toFixed(3));
        data.yAxisData = data.yAxisData.map((item) => item.toFixed(2));
        setPriceChartData(data);
      } else {
        setShowEcharts(false);
      }
    } else {
      Message.error(res.message || '获取量-收益截面模型数据失败');
      setShowEcharts(false);
    }
  };

  // 获取计算交易量截面图表数据
  const fetchPowerComputedChartDataAsync = async () => {
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await fetchPowerComputedChartData({
      sequenceId: tradeSeqId,
      unitId: stationId,
      menuCode: menuCode,
      hourOrder: echartsHourOrder,
      power: echartsPower,
      pStep: 50,
    });
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (res?.data?.xAxisData?.length) {
        setShowEcharts(true);
        let data = JSON.parse(JSON.stringify(res.data));
        data.xAxisData = data.xAxisData.map((item) => item.toFixed(2));
        data.yAxisData = data.yAxisData.map((item) => item.toFixed(2));
        setPowerChartData(data);
      } else {
        setShowEcharts(false);
      }
    } else {
      Message.error(res.message || '获取价-收益截面模型数据失败');
      setShowEcharts(false);
    }
  };

  // 刷新图形
  const echartsRefresh = () => {
    switch (selectedEcharts) {
      case EchartsType.THREE_DIMENSION:
        fetch3DChartDataAsync();
        break;
      case EchartsType.BENEFIT:
        fetchBenefitsComputedChartDataAsync();
        break;
      case EchartsType.PRICE:
        fetchPriceComputedChartDataAsync();
        break;
      case EchartsType.POWER:
        fetchPowerComputedChartDataAsync();
        break;
    }
  };

  return (
    <div className={styles.echartsShow}>
      {showEcharts ? (
        <>
          <div
            id="3dModel"
            className={`${styles.echarts3d} ${
              selectedEcharts === EchartsType.THREE_DIMENSION ? styles.show : ''
            }`}
          >
            {''}
          </div>
          <div
            id="2dModel"
            className={`${styles.echartsLine} ${
              selectedEcharts !== EchartsType.THREE_DIMENSION ? styles.show : ''
            }`}
          >
            {''}
          </div>
        </>
      ) : (
        <TRDefault type="emptysm" />
      )}
    </div>
  );
};

export default connect(({ dayRollingTradeStragety, global }) => ({
  menuCode: global.configure.menuCode,
  tradeSeqId: dayRollingTradeStragety.tradeSeqId,
  stationId: dayRollingTradeStragety.stationId,
  echartsHourOrder: dayRollingTradeStragety.echartsHourOrder,
  echartsBenefit: dayRollingTradeStragety.echartsBenefit,
  echartsBenefitStep: dayRollingTradeStragety.echartsBenefitStep,
  echartsPrice: dayRollingTradeStragety.echartsPrice,
  echartsPower: dayRollingTradeStragety.echartsPower,
  selectedEcharts: dayRollingTradeStragety.selectedEcharts,
  strategyId: dayRollingTradeStragety.strategyId,
  echartsRefreshTag: dayRollingTradeStragety.echartsRefreshTag,
}))(EchartsShow);
